<template>
  <el-upload
    v-model:file-list="fileList"
    class="upload-demo"
    action="#"
    :multiple="true"
    :auto-upload="true"
    :http-request="handleUpload"
    :before-upload="beforeUpload"
    :on-success="handleSuccess"
    :on-error="handleError"
    :limit="3"
  >
    <el-button type="primary">上传文件</el-button>
    <template #tip>
      <div class="el-upload__tip">支持jpg/png文件，大小不超过500kb</div>
    </template>
  </el-upload>
  <el-radio-group v-model="uploadAddress">
    <el-radio value="1" size="large">本地文件夹</el-radio>
    <el-radio value="2" size="large">服务器</el-radio>
  </el-radio-group>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import type { UploadProps, UploadUserFile, UploadRequestOptions } from 'element-plus'
import { ElMessage } from 'element-plus'
import { filesUpload, filesUploadDb } from '@/api/component/common'

const fileList = ref<UploadUserFile[]>([])
const uploadAddress = ref('1')
// 上传前校验（可选）
const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.size > 1024 * 1024 * 20) {
    ElMessage.error('文件大小不能超过20MB!')
    return false
  }
  console.log(rawFile)
  if (
    ![
      'image/jpeg',
      'image/png',
      'application/pdf',
      'mp3',
      'video/mp4',
      'text/plain',
      'doc',
      'docx',
      'xls',
      'xlsx',
      'ppt',
      'pptx',
      'rar',
      'zip'
    ].includes(rawFile.type)
  ) {
    ElMessage.error('仅支持JPG/PNG格式!')
    return false
  }
  return true
}
// 自定义上传方法
const handleUpload = async (options: UploadRequestOptions) => {
  // eslint-disable-next-line no-useless-catch
  try {
    const formData = new FormData()
    formData.append('file', options.file) // 字段名根据后端接口调整
    // 调用上传接口
    if (uploadAddress.value == '2') {
      const res = await filesUploadDb(formData)
      return res
    }
    const res = await filesUpload(formData)

    // 返回结果给upload组件（会触发on-success）
    return res
  } catch (err) {
    // 错误处理（会触发on-error）
    throw err
  }
}

// 上传成功回调
const handleSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  ElMessage.success('上传成功')
  // 更新文件列表状态（可选）
  uploadFile.status = 'success'
  uploadFile.url = response.data.url // 根据接口返回调整
}

// 上传失败回调
const handleError: UploadProps['onError'] = (err) => {
  ElMessage.error(`上传失败: ${err.message}`)
}
</script>
